<template>
  <div class="app-container">
    <el-page-header @back="goBack">
      <template #content>
        <span class="text-large font-600 mr-3"> 基础数据维护 </span>
      </template>
    </el-page-header>
    <el-divider />
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="客户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Download"
          @click="handleExportTemplate(1)"
          >下载客户导入模板</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Download"
          @click="handleExportTemplate(2)"
          >下载品番导入模板</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Upload"
          @click="selectImportFile(1)"
          >导入客户信息</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Download" @click="handleExport(1)"
          >导出客户信息</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Upload"
          @click="selectImportFile(2)"
          >导入客户品番信息</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Download" @click="handleExport(2)"
          >导出客户品番信息</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getTable"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tableList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="expand">
        <template #default="scope">
          <Material :customer="scope.row"></Material>
          <!-- <el-empty v-else description="不可配置" /> -->
        </template>
      </el-table-column>
      <el-table-column
        label="客户"
        align="center"
        min-width="130"
        prop="name"
        show-overflow-tooltip
      />
      <el-table-column label="备货类型" align="center" width="100" prop="type">
        <template #default="scope">
          <span v-if="scope.row.type == 1">外贸集装箱</span>
          <span v-if="scope.row.type == 2">内贸集装箱</span>
          <span v-if="scope.row.type == 3">国内卡车</span>
        </template>
      </el-table-column>
      <el-table-column
        label="样式"
        align="center"
        min-width="90"
        prop="packType"
        show-overflow-tooltip
      />
      <el-table-column
        label="托盘"
        align="center"
        min-width="100"
        prop="tray"
        show-overflow-tooltip
      />
      <el-table-column
        label="箱标签"
        align="center"
        min-width="130"
        prop="boxDesc"
        show-overflow-tooltip
      />
      <el-table-column
        label="托标签"
        align="center"
        min-width="130"
        prop="trayDesc"
        show-overflow-tooltip
      />
      <el-table-column
        label="打包带"
        align="center"
        min-width="130"
        prop="packStrap"
        show-overflow-tooltip
      />
      <el-table-column
        label="缠绕膜"
        align="center"
        min-width="130"
        prop="wrappingFilm"
        show-overflow-tooltip
      />
      <el-table-column
        label="写真"
        align="center"
        width="80"
        prop="path"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            v-if="scope.row.path"
            @click="openPreview(scope.row)"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="230"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="selectFilePath(scope.row)"
            >上传写真</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getTable"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户" />
        </el-form-item>
        <el-form-item label="备货类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">外贸集装箱</el-radio>
            <el-radio :label="2">内贸集装箱</el-radio>
            <el-radio :label="3">国内卡车</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="样式" prop="packType">
          <el-input v-model="form.packType" placeholder="请输入样式" />
        </el-form-item>
        <el-form-item label="托盘" prop="tray">
          <el-input v-model="form.tray" placeholder="请输入托盘" />
        </el-form-item>

        <el-form-item label="箱标签" prop="boxDesc">
          <el-input v-model="form.boxDesc" placeholder="请输入箱标签描述" />
        </el-form-item>
        <el-form-item label="托标签" prop="trayDesc">
          <el-input v-model="form.trayDesc" placeholder="请输入托标签描述" />
        </el-form-item>
        <el-form-item label="打包带" prop="packStrap">
          <el-input v-model="form.packStrap" placeholder="请输入打包带描述" />
        </el-form-item>
        <el-form-item label="缠绕膜" prop="wrappingFilm">
          <el-input v-model="form.wrappingFilm" placeholder="请输入缠绕膜" />
        </el-form-item>
        <!-- <el-form-item label="写真" prop="path">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            :multiple="false"
            :limit="1"
            >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">支持多文件上传，最多5个文件</div>
            </template>
          </el-upload>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="预览" v-model="uploadOpen" width="500px" append-to-body>
      <el-image
        v-if="imgPath" 
        style="width: 450; height: 400px"
        :src="imgPath"
        :zoom-rate="1.2"
        :max-scale="7"
        :min-scale="0.2"
        :preview-src-list="[imgPath]"
        show-progress
        :initial-index="4"
        fit="cover"
      />
      <video
        controls
        v-if="videoPath"
        width="450"
        height="400"
        :src="videoPath"
      >
        您的浏览器不支持视频播放
      </video>
      <el-empty v-if="otherPath" description="其他类型文件，无法预览！" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Post">
// import { listPost, addPost, delPost, getPost, updatePost } from "@/api/system/post";
import pagination from "@/components/Pagination/index.vue";
import RightToolbar from "@/components/RightToolbar/index.vue";
import Material from "@/views/material/index.vue";
import { nextTick } from "vue";
const emit = defineEmits();
const { proxy } = getCurrentInstance();
const tableList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const uploadOpen = ref(false);
const videoPath = ref();
const imgPath = ref();
const otherPath = ref();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    name: [{ required: true, message: "请输入", trigger: "blur" }],
    type: [{ required: true, message: "请输入", trigger: "blur" }],
    tray: [{ required: true, message: "请输入", trigger: "blur" }],
    packType: [{ required: true, message: "请输入", trigger: "blur" }],
    boxDesc: [{ required: true, message: "请输入", trigger: "blur" }],
    trayDesc: [{ required: true, message: "请输入", trigger: "blur" }],
    packStrap: [{ required: true, message: "请输入", trigger: "blur" }],
    wrappingFilm: [{ required: true, message: "请输入", trigger: "blur" }],
  },
});
const fileList = ref([]);
const formRef = ref();
const choiceRow = ref();

const { queryParams, form, rules } = toRefs(data);

const goBack = () => {
  emit("close");
};

const openPreview = async (row) => {
  uploadOpen.value = true;
  choiceRow.value = { ...row };
  let type = getFileType(row.path);
  console.log(row.path);
  if (type == "image") {
    videoPath.value = undefined;
    imgPath.value = `file://${row.path}`;
    otherPath.value = undefined;
  } else if (type == "video") {
    videoPath.value = `file://${row.path}`;
    imgPath.value = undefined;
    otherPath.value = undefined;
  } else {
    videoPath.value = undefined;
    imgPath.value = undefined;
    otherPath.value = "undefined";
  }
};

const fileTypeMap = {
  // 图片类型
  image: ["jpg", "jpeg", "png", "gif", "bmp", "webp"],
  // 视频类型
  video: ["mp4", "webm", "ogg", "mov", "avi", "flv"],
};

const getFileType = (fileName) => {
  // 获取文件后缀（转小写）
  const ext = fileName.split(".").pop()?.toLowerCase() || "";
  // 判断是否为图片
  if (fileTypeMap.image.includes(ext)) return "image";
  // 判断是否为视频
  if (fileTypeMap.video.includes(ext)) return "video";
  // 其他类型
  return "other";
};

const selectFilePath = async (row) => {
  choiceRow.value = { ...row };
  let path = await window.base.selectFile();
  if (path) {
    await window.base.saveFile({ id: row.id, filePath: path });
    getTable();
  }
};

window.addEventListener("upload-result", uploadResult);

function uploadResult(event) {
  if (event.detail?.success) {
    proxy.$modal.msgSuccess("上传成功");
    uploadOpen.value = false;
    getTable();
  } else {
    proxy.$modal.msgError(event.msg);
  }
}

const handleFileChange = (file) => {
  // 获取文件本地路径（注意：Electron中file.raw.path为真实路径）

  console.log(file.raw, 123);
  const filePath = file.raw.path;
  // 发送路径至主进程
  window.base.saveFile({ id: choiceRow.value.id, filePath: filePath });
  // ipcRenderer.send("upload-file-to-main", filePath);
};

/** 查询岗位列表 */
async function getTable() {
  console.log(123,"进入查询")
  loading.value = true;
  try {
    let result = await window.base.tableCustomer({ ...queryParams.value });
    console.log(result, 222);
    total.value = result.pagination.total;
    tableList.value = result.data;
  } catch (e) {
    console.log("Query Error",e)
  } finally {
    loading.value = false;
  }
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {};

  // console.log(formRef)
  // formRef.value.resetFields();
  // proxy.resetForm("formRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getTable();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
  };
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.postId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加客户";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  open.value = true;
  title.value = "修改客户";
  nextTick(() => {
    form.value = { ...row };
  });
}
/** 提交按钮 */
function submitForm() {
  // console.log(formRef.)
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        let result = await window.base.updateCustomer({ ...form.value });
        if (result.success) {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getTable();
        } else {
          proxy.$modal.msgError("修改失败");
        }
      } else {
        let result = await window.base.createCustomer({ ...form.value });
        if (result.success) {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getTable();
        } else {
          proxy.$modal.msgError("新增失败");
        }
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除？")
    .then(async function () {
      return window.base.removeCustomer({ ...row });
    })
    .then((result) => {
      console.log(result);
      if (result == "success") {
        proxy.$modal.msgSuccess("删除成功");
        nextTick(() => {
          getTable();
        });
      } else {
        proxy.$modal.msgError("删除失败");
      }
    })
    .catch(() => {});
}
/** 导出按钮操作 */
async function handleExport(type) {
  let paras = {
    type: type,
    query: { ...queryParams.value },
    fileName: type == 1 ? "客户信息.xlsx" : "客户品番信息.xlsx",
  };
  if (type == 2) {
    paras.query.name = undefined;
  }
  const savePath = await window.base.generateExcel(paras);
  if (savePath) {
    proxy.$modal.msgSuccess("导出成功");
  }
}

async function handleExportTemplate(type) {
  let parasm = {
    type: type,
    query: { ...queryParams.value, name: "给一个永远也差不出来数据的条件" },
    fileName: type == 1 ? "客户信息导入模板.xlsx" : "客户品番信息导入模板.xlsx",
  };
  const savePath = await window.base.generateExcel(parasm);
  if (savePath) {
    proxy.$modal.msgSuccess("导出成功");
  }
}

const selectImportFile = async (type) => {
  let path = await window.base.selectImportFile();
  if (path) {
    await window.base.parseExcel({ type, filePath: path });
    getTable();
  }
};

getTable();
</script>
